package com.mrent.web.controller.front;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mrent.entity.Goods;
import com.mrent.entity.Member;
import com.mrent.service.GoodsService;
import com.mrent.service.MemberService;
import com.mrent.util.Constance;
import com.mrent.util.DateUtil;
import com.mrent.util.RenderUtil;
import com.mrent.web.po.AuctionMember;

@Controller
public class GoodsAuctionController {
	
	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private MemberService memberService;
	
	
	
	//保存商品拍卖会员列表.
	private ConcurrentHashMap<String,CopyOnWriteArraySet<AuctionMember>> goodsAuctionMembers = new ConcurrentHashMap<String,CopyOnWriteArraySet<AuctionMember>>();
	//保存商品拍卖最后出价.
	private ConcurrentHashMap<String,AuctionMember> lasts = new ConcurrentHashMap<String,AuctionMember>();
	/**
	 * 拍卖加价.
	 * @param goodsNo
	 * @param addPrice
	 * @return
	 */
	@RequestMapping("/goods/auction/addPrice")
	public String addPrice(String goodsNo,Long memberId,BigDecimal auctionPrice,HttpSession session,HttpServletResponse response){
		Map<String,Object> json = new HashMap<String,Object>();
		Member member = (Member)session.getAttribute(Constance.SESSION_MEMBER_NAME);
		if(member == null){
			json.put("result", "Faile");
			json.put("ErrorCode", "-1");
			RenderUtil.renderJson(json,response);
			return null;
		}
		Goods goods = goodsService.getGoods(goodsNo);
		if(goods != null && isExpire(goods) == false){
			//出价会员信息.
			AuctionMember auctionMember = new AuctionMember();
			auctionMember.setMemberId(member.getMemberId());
			auctionMember.setMemberName(member.getMemberName());
			auctionMember.setDate(new Date());
			auctionMember.setDateLine(System.currentTimeMillis());
			auctionMember.setMemberPhoto(member.getMemberPhoto());
			auctionMember.setAuctionPrice(auctionPrice);
			auctionMember.setMemberRealName(member.getMemberRealName());
			auctionMember.setMemberSex(member.getMemberSex());
			
			BigDecimal add = auctionPrice.subtract(goods.getAuctionStartPrice());
			//判断是否比上一人出的价高.
			if(lasts.containsKey(goodsNo)){
				AuctionMember lastAuction = lasts.get(goodsNo);
				if(auctionPrice.compareTo(lastAuction.getAuctionPrice()) <= 0){
					json.put("result", "Faile");
					json.put("ErrorCode", "-2");
					RenderUtil.renderJson(json,response);
					return null;
				}
				add = auctionPrice.subtract(lastAuction.getAuctionPrice());
				lasts.put(goodsNo, auctionMember);
			}else{
				lasts.put(goodsNo, auctionMember);
			}
			//小于最小加价.
			if(add.compareTo(goods.getMinAdd())<0){
				json.put("result", "Faile");
				json.put("ErrorCode", "-3");
				RenderUtil.renderJson(json,response);
				return null;
			}
			//高于最高加价.
			if(add.compareTo(goods.getMaxAdd())>0){
				json.put("result", "Faile");
				json.put("ErrorCode", "-4");
				RenderUtil.renderJson(json,response);
				return null;
			}
			//取得会员列表.
			CopyOnWriteArraySet<AuctionMember> members = goodsAuctionMembers.get(goods.getGoodsNo());
			if(members == null){
				members = new CopyOnWriteArraySet<AuctionMember>();
				
				//定时任务，拍卖结束只要有一个人进行拍卖把商品分配.(google app engine 不支持)
				/*Date endTime = goods.getAuctionDate();
				Calendar endCal = DateUtil.getCalendar(endTime);
				endCal.set(Calendar.HOUR_OF_DAY, goods.getAuctionEndHour());
				endCal.set(Calendar.MINUTE, goods.getAuctionEndMin());
				endCal.set(Calendar.SECOND, (int)0);
				final String goodsNoFinal = goodsNo;
				Timer timer = new Timer();
				timer.schedule(new TimerTask(){
					public void run(){
						System.out.println("schedule task:"+goodsNoFinal);
						Goods goods = goodsService.getGoods(goodsNoFinal);
						AuctionMember auctionMember = lasts.get(goodsNoFinal);
						System.out.println("last auction price:" + auctionMember.getAuctionPrice());
					}
				}, endCal.getTime());*/
			}
			members.add(auctionMember);
			goodsAuctionMembers.put(goodsNo, members);
			
			json.put("result", "Success");
			RenderUtil.renderJson(json,response);
			return null;
		}
		return null;
	}
	
	/**
	 * 拍卖结束.返回最终获得者.
	 * 
	 * @param goodsNo
	 * @return
	 */
	@RequestMapping("/goods/auction/timeOut/{goodsNo}")
	public String timeOut(@PathVariable String goodsNo,HttpServletResponse response){
		AuctionMember auctionMember = lasts.get(goodsNo);
		Map<String,Object> json = new HashMap<String,Object>();
		if(auctionMember != null){
			//生成订单.
			
			//返回.
			json.put("result", "Success");
			json.put("lastAuction", auctionMember);
			RenderUtil.renderJson(json, response);
			return null;
		}else{
			json.put("result", "Faile");
		}
		return null;
	}
	
	
	
	/**
	 * 获取商品拍卖会员出价列表.
	 * @param goodsNo
	 * @return
	 */
	@RequestMapping("/goods/auction/memberList")
	public String auctionMemberList(String goodsNo,HttpServletResponse response){
		CopyOnWriteArraySet<AuctionMember> members = goodsAuctionMembers.get(goodsNo);
		if(members != null){
			RenderUtil.renderJson(members.toArray(), response);
		}
		return null;
	}
	
	
	
	/**
	 * 检查过期.
	 * 
	 * @param goods
	 * @return
	 */
	private boolean isExpire(Goods goods){
		Calendar nowCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
		Long nowTime = nowCal.getTime().getTime();
		Date auctionDate = goods.getAuctionDate();
		Calendar auctionCal = DateUtil.getCalendar(auctionDate);
		auctionCal.set(Calendar.HOUR_OF_DAY, goods.getAuctionEndHour());
		auctionCal.set(Calendar.MINUTE, goods.getAuctionEndMin());
		Long auctionTime = auctionCal.getTime().getTime();
		if( (auctionTime - nowTime)/1000 >= 0){
			return false;
		}else{
			return true;
		}
	}
	
	

}
